<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;
use Log;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;


/**
 * App\Image
 *
 * @property int $id
 * @property string $key
 * @property int $article_id
 * @property string $description
 * @property string $bucket
 * @property string $fname
 * @property string $fsize
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property int $width
 * @property int $height
 * @property string $format
 * @property-read \App\Article $article
 * @property-read mixed $key_word
 * @property-read mixed $original_image
 * @property-read mixed $quote_url
 * @property-read mixed $water_mark
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Movie[] $movies
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Show[] $shows
 * @method static \Illuminate\Database\Query\Builder|\App\Image whereArticleId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Image whereBucket($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Image whereCreatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Image whereDescription($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Image whereFname($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Image whereFormat($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Image whereFsize($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Image whereHeight($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Image whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Image whereKey($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Image whereUpdatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Image whereWidth($value)
 * @mixin \Eloquent
 * @property string $deleted_at
 * @method static \Illuminate\Database\Query\Builder|\App\Image whereDeletedAt($value)
 */
class Image extends Model
{

    //http://img.trytv.org/article/2858/img/16?imageView2/0/q/75|watermark/2/text/bW9qb1RW/font/6buR5L2T/fontsize/420/fill/I0ZGRkZGRg==/dissolve/100/gravity/NorthWest/dx/10/dy/10|imageslim

    const WATER_MARKER = 'watermark/2/text/VFJZ576O5Ymn/font/5b6u6L2v6ZuF6buR/fontsize/500/fill/I0ZDRkJGQg==/dissolve/100/gravity/NorthWest/dx/5/dy/5';
    protected $waterMaker = 'imageView2/0/q/75|watermark/2/text/bW9qb1RW/font/6buR5L2T/fontsize/420/fill/I0ZGRkZGRg==/dissolve/100/gravity/NorthWest/dx/10/dy/10|imageslim';
    protected $fillable = [
        'description',
        'article_id',
        'bucket',
        'key',
        'fname',
        'hash',
        'fname',
        'fsize',
        'width',
        'height',
        'format',
        'translation',
    ];
    protected $appends = ['url'];

    public static function boot()
    {
        parent::boot();

        self::creating(function ($model) {


            // ... code here
        });

        self::created(function ($model) {

        });

        self::updating(function ($model) {

        });

        self::updated(function ($model) {
            // ... code here
        });

        self::deleting(function ($model) {
            // ... code here
            list($bucket, $bucketMgr) = self::QINIU_BUCKET();
            $err = $bucketMgr->delete($bucket, $model->key);
            Log::info("删除图片$model->key" . $model->description);
            if ($err !== null) {
                Log::info($err->message());
            }
        });

        self::deleted(function ($model) {
            // ... code here
        });
    }

    /**
     * @return array
     */
    public static function QINIU_BUCKET(): array
    {
        $bucket = config('app.QN_bucketName');
        $accessKey = config('app.QN_accessKey');
        $secretKey = config('app.QN_secretKey');
        $bucketMgr = new BucketManager(new Auth($accessKey, $secretKey));
        return array($bucket, $bucketMgr);
    }

    static function IMAGE_URL_WITH_WATER_MARKER($key)
    {
        return config('app.QNImageUrl') . '/' . $key . '?' . self::WATER_MARKER;
    }

    public static function deleteByDescription($description)
    {
        $image = Image::where('description', $description)->first();
        $key = $image->key;
        $image->delete();


        $accessKey = config('app.QN_accessKey');
        $secretKey = config('app.QN_secretKey');

//初始化Auth状态：
        $auth = new Auth($accessKey, $secretKey);

//初始化BucketManager
        $bucketMgr = new BucketManager($auth);

//你要测试的空间， 并且这个key在你空间中存在
        $bucket = env('QN_bucketName');

//删除$bucket 中的文件 $key
        $err = $bucketMgr->delete($bucket, $key);
        echo "\n====> delete $key : \n";
        if ($err !== null) {
            var_dump($err);
        } else {
            echo "Success!";
        }


    }

    /**
     * 抓取网络图片
     * @param $url 网络图片url
     * @param $key 七牛key
     * @param $alt alt
     * @return mixed 图片Image instance
     */
    static function fetchUrlWithKey($url, $key, $alt): Image
    {
        $image = self::where('fname', $url)->first();
        if ($image) {
            return $image;
        }
        list($bucket, $bucketMgr) = self::QINIU_BUCKET();
        list($ret, $err) = $bucketMgr->fetch($url, $bucket, $key);
        if ($err !== null) {
            Log::info('图片下载失败' . $url);
            return new Image();
        } else {
            $image = self::firstOrNew(['key' => $key]);
            $image->format = $ret['mimeType'];
            $image->fsize = $ret['fsize'];
            $image->fname = $url;
            $image->description = $alt;
            $image->bucket = $bucket;
            $image->save();
            return $image;
        }


    }

    static function deleteByFname($fname)
    {
        Image::where(compact('fname'))->delete();
    }

    /**
     * ueditor 上传图片
     * @param UploadedFile $file
     * @param string $key
     * @return Image
     */
    static function UploadServerFileToQiniu(UploadedFile $file, string $key, int $article_id): Image
    {
        $fsize = $file->getClientSize();
        $fname = $file->getClientOriginalName();
        $image = Image::firstOrNew(compact('fname', 'fsize'));
        if ($image->id > 0) {
            return $image;
        }
        // 需要填写你的 Access Key 和 Secret Key
        $bucket = config('app.QN_bucketName');
        $accessKey = config('app.QN_accessKey');
        $secretKey = config('app.QN_secretKey');
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
// 要上传文件的本地路径
        $filePath = $file->path();
// 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
// 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        //echo "\n====> putFile result: \n";
        if ($err !== null) {
            var_dump($err);
            Log::alert('UploadServerFileToQiniu 图片上传失败' . $err->message());
            dd('ueditor 七牛上传图片失败');
        } else {
            $image->key = $ret['key'];
            $image->bucket = $bucket;
            $image->article_id = $article_id;
            $image->save();
            return $image;
        }
    }

    public function article()
    {
        return $this->belongsTo('App\Article');
    }

    public function shows()
    {
        return $this->belongsToMany('App\Show');
    }

    public function movies()
    {
        return $this->belongsToMany('App\Movie');
    }

//http://developer.qiniu.com/code/v6/api/kodo-api/image/imageview2.html

    public function getOriginalImageAttribute()
    {
        $baseUrl = config('app.QNImageUrl');
        return $baseUrl . '/' . $this->key . '?';
    }

    public function getUrl()
    {
        return $this->imgURL();
    }

    public function imgURL()
    {
        $baseUrl = config('app.QNImageUrl');
        return $baseUrl . '/' . $this->key . '?' . $this->waterMaker;
    }

    public function getUrlAttribute()
    {
        return $this->imgURL();
    }

    public function squareImage($size = 300)
    {
        $waterMaker = 'imageView2/1/w/' . $size . '/h/' . $size . '/interlace/1';
        $baseUrl = config('app.QNImageUrl');
        return $baseUrl . '/' . $this->key . '?' . $waterMaker;
    }

    public function imageWH($width = 500, $height = 300)
    {
        $waterMaker = 'imageView2/1/w/' . $width . '/h/' . $height . '/interlace/1';
        $baseUrl = config('app.QNImageUrl');
        return $baseUrl . '/' . $this->key . '?' . $waterMaker;
    }

    public function getKeyWordAttribute()
    {
        $keyWord = '';
        if ($this->show) {
            $keyWord .= $this->show->name_en . '  ' . $this->show->name_zh;
        }

        if ($this->article) {
            $keyWord .= $this->article->title;
        }
        return $keyWord;
    }

    public function imageModeSizeWaterMark($mode = 1, $width = 200, $height = 200, $iswatermark = true)
    {
        if ($mode > 5) {
            $mode = 5;
        }
        if ($mode < 1) {
            $mode = 1;
        }

        $waterMaker = 'imageView2/' . $mode . '/w/' . $width . '/h/' . $height . '/interlace/1';
        if ($iswatermark) {
            $waterMaker = "{$waterMaker}/{$this->waterMaker}";
        }


        $baseUrl = config('app.QNImageUrl');

        return $baseUrl . '/' . $this->key . '?' . $waterMaker;
    }

    public function getWaterMarkAttribute()
    {
        $waterMaker = 'watermark/2/text/VFJZ576O5Ymn/font/5b6u6L2v6ZuF6buR/fontsize/500/fill/I0ZDRkJGQg==/dissolve/100/gravity/NorthWest/dx/5/dy/5';
        $baseUrl = config('app.QNImageUrl');
        return $baseUrl . '/' . $this->key . '?' . $waterMaker;
    }

    public function getQuoteUrlAttribute()
    {

        $waterMaker = 'imageMogr2/gravity/NorthWest/crop/620x350/interlace/1';
        $baseUrl = config('app.QNImageUrl');
        return $baseUrl . '/' . $this->key . '?' . $waterMaker;
    }
}
